package com.bbb.blogservice.service.common;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;

@Service(value = "commonService")
public class CommonServiceImpl implements CommonService{

    @Autowired
    private JdbcTemplate writeTemplate;

    @Override
    @Transactional(isolation = Isolation.READ_UNCOMMITTED, rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public Long getGenerateId(String tableName) {

        StringBuilder selectSql = new StringBuilder(" SELECT ");
        selectSql.append(" id_num ");
        selectSql.append(" FROM ");
        selectSql.append(" id_record ");
        selectSql.append(" where ");
        selectSql.append(" table_name = ? ");
        selectSql.append(" limit 1 ");
        selectSql.append(" FOR UPDATE; ");

        Long id = writeTemplate.queryForObject(selectSql.toString(), new Object[]{tableName}, Long.class);

        StringBuilder updateBuilder = new StringBuilder("  update id_record set id_num = id_num + 1 where table_name = ? ");
        writeTemplate.update(updateBuilder.toString(), new Object[]{tableName});

        return id;
    }
}
